﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Sustainalytics.ESGRatings.BusinessLogic.Computing.Utils
{
    public static class ListExtensions
    {
        public static T Peek<T>(this IList<T> stack)
        {
            return stack[stack.Count - 1];
        }

        public static T Pop<T>(this List<T> stack)
        {
            var lastIndex = stack.Count - 1;
            var last = stack[lastIndex];

            stack.RemoveAt(lastIndex);
            return last;
        }

        public static void Push<T>(this IList<T> stack, T item)
        {
            stack.Add(item);
        }

        public static IEnumerable<T> Yield<T>(this T item)
        {
            yield return item;
        }
    }

    public static class ExceptionUtility
    {
        private const int exceptionMaxInnerLevel = 5;

        public static string GetInfo(Exception exception)
        {
            return exception != null ? exception.ToString() : string.Empty;
        }

        public static string GetInfo(Exception exception, bool includeInnerExceptions)
        {
            StringBuilder sb = new StringBuilder();
            Exception currentException = exception;
            string separator = string.Empty;
            int level = exceptionMaxInnerLevel;
            while (currentException != null && level > 0)
            {
                sb.Append(
                    string.Format(
                        "{2}Exception:\"{0}\" StackTrace:\"{1}\"\n", 
                        currentException.Message, 
                        currentException.StackTrace, 
                        separator));
                if (!includeInnerExceptions)
                {
                    break;
                }

                separator = "\t";

                currentException = currentException.InnerException;
                --level;
            }

            return sb.ToString();
        }
    }
}